var util=require('../../utils/util.js')
Page({
  data: {
    num: 0,
    noAddress: false,
    arr: [
      { id: 0, name: "张三 先生", phone: "123456789", address:"启梦创业广场1A158-159"},
      { id: 1, name: "张三 先生", phone: "123456789", address: "启梦创业广场1A158-159" },
      { id: 2, name: "张三 先生", phone: "123456789", address: "启梦创业广场1A158-159" },
    ],
  },
  onLoad:function(){
    
  },
  onShow:function(){
    this.getContactList();
  },
  getContactList:function(){
    var that=this;
    var url=util.url.user_address_list;
    util.fetchGet(
      url,
      function(ret){
        that.setData({
          arr:ret.data
        })
      }
    )
  },
  chooseAddress: function(e) {
    var id = e.currentTarget.dataset.id;    
    var back=this.setDefault(id);
    if (back.unid || back.unid==0){
      var url = util.url.user_address_setdefault;
      url += "?id=" + id + "&unid=" +back.unid;
      util.fetchGet(
        url,
        function(ret){

        }
      )
    }
  },
  setDefault:function(id){
    var arr=this.data.arr;
    var unid=0;
    for(var i=0;i<arr.length;i++){      
      if (id == arr[i].id){
        if (arr[i].isDefault == 1) {
          return {id:0};
        }else{
          arr[i].isDefault=1;
        }        
      }else{
        if (arr[i].isDefault == 1) {
          arr[i].isDefault=0;
          unid=arr[i].id;
        }
      }
    }
    this.setData({
      arr: arr
    })
    return {unid:unid};
  },
  addAddress: function() {
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },
  delAddress: function() {
     var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除该地址吗？',
      success: function (res) {
        if (res.confirm) {
          var index = that.data.num;
          var arr = that.data.arr;
          arr.splice(index, 1);
          that.setData({
            arr: arr
          })
        }
      }
    })
    
  },
  toEdit: function(e) {
    var id = e.currentTarget.dataset.id;
    var userAddress={};
    var arr=this.data.arr; 
    for (var i = 0; i < arr.length; i++) {
      if (id == arr[i].id) {
        userAddress = arr[i]
      }
    }
    wx.navigateTo({
      url: '../addAddress/addAddress?userAddress=' + JSON.stringify(userAddress),
    })
  },
  goToOrder:function(e){
    var pages = getCurrentPages();//页面指针数组 
    var prepage = pages[pages.length - 2];//上一页面指针 
    var route=prepage.route;
    if (route != 'pages/submitOrder/submitOrder'){
      return ;
    }
    var id = e.currentTarget.dataset.id;
    var arr=this.data.arr;
    var userAddress={};
    for (var i = 0; i < arr.length; i++) {
      if (id == arr[i].id) {
        userAddress = arr[i]
      }
    }
    prepage.setUserAddress(userAddress);
    wx.navigateBack()
  }
})